<template>
    <div id="toubaoye">
        <my-header></my-header>
        <div class="main">
            <div class="insur-content item">
                <h2 class="title" style="margin-left: 0">保障内容</h2>
                <ul>
                    <li class="flex-box">
                        <div class="yes-icon">航空意外全残或身故 <span class="color-yellow">1000万</span></div>
                    </li>
                    <li class="flex-box">
                        <div class="yes-icon">自驾车意外全残或身故 保额<span class="color-yellow">10万</span> 法定节假日<span class="color-yellow">30万</span></div>
                    </li>
                    <li class="flex-box">
                        <div class="yes-icon">公共交通意外全残或身故 保额<span class="color-yellow">10万</span> 法定节假日<span class="color-yellow">30万</span></div>
                    </li>
                </ul>
                <p class="info">说明：仅年满18周岁的被保险人享有自驾车和公共交通意外责任</p>
            </div>
            <div class="insur-info item">
                <h2 class="title">投保人信息(被保人为投保人本人)</h2>
                <ul v-if="clientInfo.applicantName">
                    <li class="flex-box">
                        <span>姓名</span>
                        <span>{{ clientInfo.applicantName }}</span>
                    </li>
                    <li class="flex-box">
                        <span>身份证号码</span>
                        <span>{{ clientInfo.idNo }}</span>
                    </li>
                    <li class="flex-box">
                        <span>身份证有效期</span>
                        <span>{{ clientInfo.idValidityDate.split(' ')[0] }}</span>
                    </li>
                    <li class="flex-box">
                        <span>手机号码</span>
                        <span>{{ clientInfo.mobileNo.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3') }}</span>
                    </li>
                    <li class="flex-box">
                        <span>邮政编码</span>
                        <span>{{ clientInfo.postCode }}</span>
                    </li>
                    <li class="detail-adress flex-box">
                        <span>详细地址</span>
                        <span>{{ clientInfo.contactAddr }}</span>
                    </li>
                </ul>
            </div>
            <div class="insur-benifit item">
                <ul>
                    <li class="title border-del-b flex-box">
                        <span>身故受益人</span>
                        <div>
                            <button class="button" v-for="(item, index) in insureData.benefnos"
                                    @click="benefnoToggle(index)"
                                    :class="{'btn-active': item.active}">{{ item.name }}
                            </button>
                        </div>
                    </li>
                </ul>
                <div v-show="insureData.benefnos[1].active">
                    <div v-for="(item, index) in formData.beneficiarys">
                        <div class="design-title">
                            <span>指定受益人{{ index + 1 }}</span>
                            <div class="collapse" @touchend="switchBenefnoContent(item, index)">
                                <span class="collapseArrow" :class="item.dir"></span>
                            </div>
                            <a class="delete-person" @touchend="delBenefno(index)" v-show="index !== 0">删除受益人</a>
                        </div>
                        <ul class="benifit-info" v-show="item.dir === 'down'">
                            <li class="flex-box">
                                <span>身故受益人是被保险人的</span>
                                <div>
                                    <button class="button"
                                            v-for="(relation, relInx) in item.relationshipWithInsurantArr"
                                            :class="{'btn-active': relation.active}"
                                            @touchend="relativeToggle(index, relInx)">{{ relation.name }}
                                    </button>
                                </div>
                            </li>
                            <li class="flex-box">
                                <span>指定受益人姓名</span>
                                <input type="text" placeholder="输入受益人姓名" v-model.trim="item.name"/>
                            </li>
                            <li class="flex-box">
                                <span>受益顺序</span>
                                <div>
                                    <button class="button" v-for="(order, orderInx) in item.benefOrderArr"
                                            :class="{'btn-active': order.active}"
                                            @touchend="orderToggle(index, orderInx)">{{ order.name }}
                                    </button>
                                </div>
                            </li>
                            <li class="flex-box">
                                <span>受益比例</span>
                                <div>
                                    <input type="tel" class="rate" v-model.trim="item.benefRate" maxlength=3/>%
                                </div>
                            </li>
                            <li class="flex-box">
                                <span>身份证号码</span>
                                <input type="text" placeholder="输入受益人身份证号码" maxlength="18" v-model.trim="item.idno"/>
                            </li>
                        </ul>
                    </div>
                    <div class="add-person" v-show="formData.addBenefnoFlag">
                        <a @touchend="addBenefno" class="icon-add">增加受益人</a>
                    </div>
                </div>
            </div>
            <div class="insur-period item">
                <ul>
                    <li class="title flex-box" >保险期间</li>
                    <li class="flex-box " style="justify-content: space-around;-webkit-justify-content: space-around">
                        <div class="time"><span>{{ durationDate.start }} <br/>00:00:00起</span></div>
                        <div class="collapse"><div class="collapseArrow right"></div></div>
                        <div class="time"><span>{{ durationDate.end }} <br/>24:00:00止</span></div>
                    </li>
                </ul>
            </div>
            <div class="phone item">
                <ul>
                    <li class="flex-box" style="padding-bottom: 0">
                        <div>验证手机
                            <div class="help" @touchend="showTelTips">
                                <div class="tooltip" v-show="insureData.telTips">该号码为您上份保单使用的手机号</div>
                            </div>
                        </div>
                        <span>{{ clientInfo.mobileNo && clientInfo.mobileNo.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3') }}</span>
                    </li>
                    <li class="flex-box">
                        <div>
                            验证码
                        </div>
                        <div class="align-right">
                            <input type="text" placeholder="输入验证码" v-model.trim="code" maxlength="7" class="ui-ta-l"/>
                            <button class="button btn-active" @touchend="submit('send')"
                                    :class="{ 'btn-disable': smsCodeClassFlag} ">{{ smsCodeText }}
                            </button>
                        </div>
                    </li>
                </ul>
            </div>
            <div class="confirm-check item">
                <ul>
                    <li class="flex-box">
                        <div class="checkbox uncheck" :class="{checked: insureData.agreement}"
                             @touchend="agreementToggle"></div>
                        <div class="checkboxInfo">
                            <p>本人已阅读
                                <router-link :to="{ name: 'protocol', params: { file: 'agreemeng_qwzl_ywx.pdf', backPath: backPath } }">
                                    《平安千万尊旅意外伤害保险》所涉及条款
                                </router-link>
                                、
                                <router-link :to="{ name: 'protocol', params: { file: 'qwzl_sm.pdf', backPath: backPath } }">《投保人声明与授权》
                                </router-link>
                                的全部内容,了解并接受包括免除保险公司责任条款、犹豫期、费用扣除、退保、保单现金价值等重要事项。
                            </p>
                        </div>
                    </li>
                    <li class="flex-box">
                        <div class="checkbox uncheck" :class="{checked: insureData.apply}" @touchend="applyToggle"></div>
                        <div class="checkboxInfo">
                            <p>若本人申请平安财富天赢、赢越人生或者赢聚一生保险合同犹豫期内均退保,则本人将同时申请解除本主险合同。</p>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
        <div class="confirm-btn-wrap ui-ta-c"><a class="confirm-btn ui-ta-c" @touchend="submit('verify')">确认领取</a></div>
    </div>
</template>
<script>
  import { API } from 'config'
  import { mapGetters, mapActions, mapMutations } from 'vuex'
  import MyHeader from 'components/myHeader'
  import checker from 'lib/checker'

  let orderArr = function () {
    return [
      { active: true, val: 1, name: '第一' },
      { active: false, val: 2, name: '第二' },
      { active: false, val: 3, name: '第三' }
    ]
  }

  export default {
    name: 'Insure',
    data() {
        let clientInfo = JSON.parse(sessionStorage.getItem('indexData')) || {}
        // 计算时间
        const getDurationDate = function(timestamp) {
          let start, end,
            basicDate = new Date('2017-01-01'),
            d = new Date(timestamp)
          if (d.getTime() < basicDate.getTime()) {
            start = transformDateStr(basicDate)
            end = transformDateStr((new Date('2017-12-31')))
          }
          else {
            let _start_date = new Date((d.setDate(d.getDate()+1)))
            let _end_date = new Date((d.setDate(d.getDate()+364)))
            start = transformDateStr(_start_date)
            end = transformDateStr(_end_date)
          }
          return {
            start: transformDate(start),
            end: transformDate(end)
          }
        }
        // 处理时间格式 ios d.getFullYear() toLocaleDateString()返回的是2017年1月1日 中文
        const transformDateStr = (s) => {
            //return s.toLocaleDateString().replace(/(\/|[\u4e00-\u9fa5])/g, '-').replace(/-$/, '')
            return s.getFullYear() + '-' + (s.getMonth()+1) + '-' + s.getDate()
        }

        // 处理时间格式 ios d.getFullYear() toLocaleDateString()返回的是2017年1月1日 中文
        const transformDate = (s) => {
          let _r = s.split('-').map((s) => {
            if (s.length === 1) {
              s = '0' + s
            }
            return s
          })
          // oppo手机返回是10/10/2016,reverse处理
          // _r[0].length === 2 && _r.reverse()
          return _r.join('-')
        }

      return {
        codeRequest: { // 保留时间戳、验证码半个小时内只允许请求3次, flag 是否允许请求
          date: + new Date,
          flag: true
        },
        code: '',
        smsCodeText: '获取验证码',
        smsCodeClassFlag: false,
        signFactor: '', // 验证码校验所需因子，发送验证成功会返回该字段
        formData: {
          benefitFlag: 0, //对应benefnos默认值的val
          appointmentEffDate: 0, //指定生效日
          addBenefnoFlag: true,
          beneficiarys: []
        },
        clientInfo: clientInfo,
        durationDate: getDurationDate(clientInfo.timestamp || +new Date()),
        backPath: '/qwzl/insure'
      }
    },
    components: {
      MyHeader
    },
    computed: {
      ...mapGetters(['insureData'])
    },
    created() {
      //为指定添加一个默认受益人,此时页面不可见
      this.addBenefno(),
      (() => {
        // 初始化formData的flowId、appointmentEffDate参数
        this.formData.flowId = this.clientInfo.flowId
        this.formData.appointmentEffDate = this.durationDate.start.replace(/-/g, '')
        this.formData.benefitFlag = this.insureData.benefitFlag
      })()
    },
    watch: {},
    methods: {
      ...mapActions(['showLoading', 'hideLoading', 'showAlert', 'hideAlert', 'benefnoToggle', 'showTelTips', 'hideTelTips',
              'agreementToggle', 'applyToggle']),
      addBenefno: function () {
      let beneficiarys = this.formData.beneficiarys
        beneficiarys.map(function (item) {
          let oldOrderArr = orderArr().slice(item.benefOrderArr.length, beneficiarys.length + 1)
          item.benefOrderArr = [...item.benefOrderArr, ...oldOrderArr]
          return item
        })
        beneficiarys.push({
          dir: 'down',
          name: '',
          birthday: '', //生日、性别根据输入的身份证取
          sex: '',
          idType: '1',
          idno: '',
          relationshipWithInsurant: '2', // 与被保人关系
          relationshipWithInsurantArr: [
            { active: true, val: 2, name: '配偶' },
            { active: false, val: 3, name: '父母' },
            { active: false, val: 4, name: '子女' }
          ],
          benefOrderArr: orderArr().slice(0, beneficiarys.length + 1),
          benefOrder: '1', // 受益顺序
          benefRate: '', //比例
          benefno: beneficiarys.length // 受益人序号
        })
        if (beneficiarys.length >= 3) {
          this.formData.addBenefnoFlag = false
        }
      },
      showTelTips: function () {
        this.$store.dispatch('showTelTips')
        setTimeout(() => {
          this.$store.dispatch('hideTelTips')
        }, 2500)
      },
      benefnoToggle: function (index) {
        //benefitFlag
        this.$store.dispatch('benefnoToggle', index)
        this.formData.benefitFlag = this.insureData.benefitFlag
      },
      relativeToggle: function (index, relInx) {
        let cur = this.formData.beneficiarys[index]
        cur.relationshipWithInsurantArr.forEach(item => {
          item.active = false
        })
        let curRelation = cur.relationshipWithInsurantArr[relInx]
        curRelation.active = true
        cur.relationshipWithInsurant = curRelation.val
        this.formData.beneficiarys.splice(index, 1, cur)
      },
      orderToggle: function (index, relInx) {
        let cur = this.formData.beneficiarys[index]
        cur.benefOrderArr.forEach(item => {
          item.active = false
        })
        let curOrder = cur.benefOrderArr[relInx]
        curOrder.active = true
        cur.benefOrder = curOrder.val
        this.formData.beneficiarys.splice(index, 1, cur)
      },
      delBenefno: function (index) {
        let beneficiarys = this.formData.beneficiarys
        if (beneficiarys.length <= 3 && beneficiarys.length > 1) {
          this.formData.addBenefnoFlag = true
          beneficiarys.map((item) => {
            item.benefOrderArr = orderArr().slice(0, beneficiarys.length - 1)
            return item
          })
          beneficiarys.splice(index, 1)
        }
      },
      switchBenefnoContent: function(item, index) {
        let active = this.formData.beneficiarys[index]
        if (item.dir === 'up') {
          active.dir = 'down'
        }
        else {
          active.dir = 'up'
        }
        this.formData.beneficiarys.splice(index, 1, active)
      },
      submit: function (type) {
        if (this.smsCodeClassFlag && type === 'send') { return }
        // 当前页面中，session有效期内只允许请求5次验证码 codeCount
        let codeCount = sessionStorage.getItem('codeCount') || 1
        const countdown = (time) => {
            this.smsCodeClassFlag = true
            let timerId = setInterval(() => {
              if((time--) < 1) {
                clearInterval(timerId);
                this.smsCodeClassFlag = false
                this.smsCodeText = '重新获取'
              }
              else {
                this.smsCodeText = `${time}S后重新获取`
              }
            }, 1000);
          }
        const getSmsCode = () => {
          this.$http.post(`${API}/generateMFAInfo.shtml`, {
            clientName: this.clientInfo.applicantName,
            idNo: this.clientInfo.idNo,
            agentNo: this.clientInfo.agentNo,
            flowId: this.clientInfo.flowId,
            sms_action: type,
            accountMobile: this.clientInfo.mobileNo,
            otpExtContent: '',
            signFactor: this.signFactor,
            dynamicPassword: this.code
          })
          .then((response) => {
            let result = JSON.parse(response.body)
            if (result.otpStatus === 'Y') {
              if (type === 'send') {
                if (codeCount && codeCount <= 5) {
                  codeCount = Number(codeCount) + 1
                }
                sessionStorage.setItem('codeCount', codeCount)
                this.signFactor = result.signFactor
                countdown(121)
              }
              else {
                // 将请求参数放在session中，传到结果页面
                // 不允许返回，android物理返回键跳转到index页面
                setTimeout(() => {
                  this.$router.replace('/qwzl/result')
                }, 400)
              }
            }
            else {
              this.$store.dispatch('showAlert', result.message)
            }
          })
          .catch(function(response) {
            this.$store.dispatch('showAlert', '哎呀，系统开小差了，请刷新页面后重新操作~')
          })
        }
        if (type === 'send') {
          if (codeCount && codeCount > 5) {
            this.$store.dispatch('showAlert', '您的操作请求太频繁，请半个小时后操作~')
            return
          }
        }
        else {
          if (this.formData.benefitFlag == 1) {
            // 校验受益人
            const checkBenefRate = (val) => {
              let msg = false
              if (!/^\d{1,3}$/.test(val)) {
                msg = '请正确填写受益比率'
              }
              else if (val > 100) {
                msg = '受益比例值不能大于100'
              }
              return msg
            }
            let result = false
            let benefData = {} // 用于保存受益人顺序和比例 key: Strign 受益人顺序，value: Array 当前顺序下的比例
            let beneficiarys = this.formData.beneficiarys
            for (let i=0, l=beneficiarys.length; i<l; i++) {
              let item = beneficiarys[i]
              let name = checker.checkNameBeneficiary(item.name)
              let benefRate = checkBenefRate(item.benefRate)
              let idno = checker.checkIdNo(item.idno)
              //若身份证校验通过，将生日和性别截取
              if (!idno) {
                item.birthday = item.idno.substr(6, 8)
                let sex = item.idno.length === 18 ? item.idno.substr(16, 1) : item.idno.substr(14, 1)
                item.sex = sex % 2 === 0 ? 'F' : 'M'
              }
              result = name || benefRate || idno
              if (benefData[item.benefOrder]) {
                benefData[item.benefOrder].push(item.benefRate)
              }
              else {
                benefData[item.benefOrder] = [item.benefRate]
              }
              if (result) {
                break;
              }
            }
            if (result) {
              this.$store.dispatch('showAlert', result)
              return
            }
            let beneSum = 0
            for (let bene in benefData) {
              benefData[bene].forEach((m) => {
                beneSum += Number(m)
              })
              if (beneSum == 100) {
               beneSum = 0
              }
              else {
                break;
              }
            }
            if (beneSum % 100 !== 0) {
              this.$store.dispatch('showAlert', '同一顺位受益人的受益比例之和必须为1')
              return
            }
          }
          if (!this.code) {
            this.$store.dispatch('showAlert', '验证码不能为空')
            return
          }
          if (!/^\d{7}$/.test(this.code)) {
            this.$store.dispatch('showAlert', '请输入正确的验证码')
            return
          }
          if (!this.insureData.agreement || !this.insureData.apply) {
            this.$store.dispatch('showAlert', '请阅读相关条款后领取喔~')
            return
          }
          // 不能直接跳转，会导致取不到session里面的insureData值，估计是有延时
          sessionStorage.setItem('insureFormData', JSON.stringify(this.formData))
        }
        getSmsCode()
      }
    }
  }


</script>
<style lang="scss">
    #toubaoye {
        color: #666;
        padding-top: 0.8rem;
        .border-del-b {
            border-bottom: 0 !important
        }
        .item {
            background: #fff;
            margin-bottom: 0.1rem;
        }
        .title {
            font-size: 0.34rem;
            color: #333;
            padding: 0.2rem 0.3rem 0.2rem 0;
            margin-left: 0.3rem;
            border-bottom: 1px solid #e0e0e0;

        }
        .checkbox {
            display: inline-block;
            width: 0.38rem;
            height: 0.38rem;
        }
        .checkboxInfo {
            width: 90%;
            font-size: 0.24rem;
            line-height: 0.4rem;
            margin-left: 0.1rem;
            a {
                color: #eb520e;
            }
        }
        .main {
            margin-top: 0.2rem;
        }
        .insur-content {
          border-bottom: 1px solid #e0e0e0;
          padding-left: 0.3rem;
        .title {
          padding-left: 0;
        }
        li {
          color: #666;
          border: none;
          font-size: .28rem;
          padding-bottom: 0;
          padding-right: 0;
          /*span {*/
          /*color: #eb520e;*/
          /*}*/
        }
        .info {
          font-size: 0.24rem;
          padding: 0.1rem 0.3rem 0.26rem 0.3rem;
          color: #999;
        }
        .pdf {
          font-size: 0.24rem;
          border-top: 1px solid #e0e0e0;
          padding-left: 0.3rem;
          line-height: 0.9rem;
          color: #eb520e;
        }
        }
        .insur-info {
            .detail-adress {
                :first-child {
                    white-space: nowrap;
                }
                :last-child {
                    text-align: right;
                    padding-left: 0.4rem;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;
                }
            }
        }
        .insur-benifit {
            .design-title {
                font-size: 0.32rem;
                background: #ececec;
                & > span {
                    display: inline-block;
                    color: #eb520e;
                    padding: 0.2rem 0.3rem;
                }
                .collapse {
                    float: right;
                    width: 0.8rem;
                    height: 0.8rem;
                }
            }
            .benifit-info {
                background: #f5f5f5;
                li {
                    border-bottom: 1px solid #e0e0e0;
                }
                .rate {
                    width: 0.6rem;
                    background: #fff;
                    border-radius: 0.1rem;
                    padding: 0.05rem 0;
                    margin-right: 0.1rem;
                }
            }
            .circle {
                display: inline-block;
                width: 0.26rem;
                height: 0.26rem;
                margin-right: 0.05rem;
                img {
                    width: 100%;
                }
            }
            .delete-person {
                padding: 0.2rem 0.3rem .2rem .4rem;
                color: #eb520e;
                font-size: 0.24rem;
                float: right;
                background: url(~assets/img/common/delete.png) 0 50% no-repeat;
                background-size: .28rem;
            }
            .add-person {
                padding: 0.2rem 0.3rem;
                color: #eb520e;
                font-size: 0.24rem;
                text-align: right;
            }
            .icon-add {
                padding-left: .4rem;
                background: url(~assets/img/common/add.png) 0 50% no-repeat;
                background-size: .28rem;
            }
        }
        .phone {
            .help {
                display: inline-block;
                margin-left: 0.04rem;
                font-size: 0.2rem;
                width: 0.3rem;
                height: 0.3rem;
                text-align: center;
                position: relative;
                background: url(~assets/img/common/help.png) 0 100% no-repeat;
                background-size: .25rem .25rem;
                img {
                    width: 100%;
                    vertical-align: top;
                }
                .tooltip {
                    height: 1rem;
                    width: 4.2rem;
                    line-height: 0.6rem;
                    background: url("~assets/img/dearGuest/tips.png") no-repeat;
                    position: absolute;
                    white-space: nowrap;
                    top: -0.8rem;
                    color: #fff;
                    font-size: .25rem;
                    background-size: contain;
                }
            }
            input {
                display: inline-block;
                padding: .2rem 0;
                height: .72rem;
                width: 1.94rem;
                color: #bbb;
                text-align: center;
                border-radius: 0.06rem;
                border: 1px solid #e0e0e0;
                vertical-align: middle;
            }
            button {
                height: 0.72rem;
                width: 1.74rem;
            }
            .btn-disable {
                width: 2.3rem;
                background: #aaa9a8;
                color: #fff;
            }
        }
        .confirm-check {
            li {
                align-items: flex-start;
                &:first-child {
                    padding-bottom: 0;
                }
            }
        }
    }
</style>
